package edu.utexas.ipc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;

public class IPC {

	final int processCount;
	final int processID;
	final InetSocketAddress localAddress;
	final List<InetSocketAddress> serverList;
	Clock clock;
	Linker linker;
	Multiplexer multiplexer;
	ConnectHandler connHdl;
	Connector connector;
	
	public IPC(int processID, InetSocketAddress localAddress, List<InetSocketAddress> serverList) {
		this.processCount = serverList.size();
		this.processID = processID;
		this.localAddress = localAddress;
		this.serverList = serverList;
		
		// create internal objects and link them together
		//this.clock = new LamportClock();
		this.clock = new DirectClock(processCount, processID);
		this.linker = new Linker(processID, processCount);
		this.multiplexer = new Multiplexer(clock, linker);
		this.connHdl = new ConnectProcessHandler(clock, linker, multiplexer);
		this.connector = new Connector(connHdl);
	}
	
	public void connect() throws IOException {		
		connector.connect(localAddress, serverList);
	}
	
	public Connection openConnection(String tag) {
		return multiplexer.openConnection(tag);
	}
	
	public Mutex openMutex(String tag) {
		Connection connection = openConnection("__mutex__" + tag);
		return new LamportMutex(connection, clock, processID, processCount);
	}
	
	public void close() {
		linker.close();
		connector.close();
	}
}
